package com.foreknow.dao.impl;

import com.foreknow.dao.GuestbookDao;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.Guestbook;
import com.foreknow.util.OraclePagination;
import com.foreknow.util.Pagination;

import java.sql.SQLException;
import java.util.List;

public class GuestbookDaoImpl extends BaseDAO implements GuestbookDao {
    /**
     * 添加
     * @param guestbook
     * @return
     * @throws SQLException
     */
    @Override
    public boolean addMessage(Guestbook guestbook) throws SQLException {
        String sql="insert into guestbook(name,phone,email,title,content,createdtime) values(?,?,?,?,?,?)";
        int x = this.jdbcTemplate.update(sql,guestbook.getName(),guestbook.getPhone(),guestbook.getEmail(),guestbook.getTitle(),guestbook.getContent(),guestbook.getCreatedtime());
        return x==1;
    }

    /**
     * 查询所有留言信息
     * @return
     */
    @Override
    public List<Object> getQueryAll() {
        String sql = "select * from guestbook";
        EntityMapping mapping = this.mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = this.jdbcTemplate.query(sql,mapping);
        return list;
    }

    /**
     * 根据id删除留言信息
     * @param id
     * @return
     */
    @Override
    public boolean deleteById(Integer id) throws SQLException{
        String sql="delete from guestbook where id=?";
        int update = this.jdbcTemplate.update(sql, id);
        return update==1;
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public Guestbook getIdQuery(Integer id) {
        String sql="select * from guestbook where id=?";
        EntityMapping mapping = this.mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = this.jdbcTemplate.query(sql, mapping, id);
        if (list.size()>0){
            return (Guestbook) list.get(0);
        }else{
            System.out.println("dao层查询空");
            return null;
        }
    }

    /**
     * 修改信息
     * @return
     * @throws SQLException
     */
    @Override
    public boolean updateInfo(Guestbook gb) throws SQLException {
        String sql="update guestbook set name=?,phone=?,email=?,title=?,content=?,createdtime=? where id=?";
        int update = this.jdbcTemplate.update(sql,gb.getName(),gb.getPhone(),gb.getEmail(),gb.getTitle(),gb.getContent(),gb.getCreatedtime(),gb.getId());
        return update==1;
    }

    /**
     * 分页查询信息
     * @param pageSize 每页显示的记录数
     * @param pageNumber  当前页码
     * @return
     * @throws SQLException
     */
    @Override
    public Pagination getGuestbookByPage(int pageSize, int pageNumber) throws SQLException {
    String sql="select * from guestbook";
    Pagination pagination=new OraclePagination(sql,pageSize,pageNumber);
    return pagination;
    }

}
